<template>
    <view class="recycle_logistics_form-container">
        
        <u-form :model="form" :error-type="['toast']" ref="uForm">
            <!-- 寄件地址 -->
            <view class="shipper-address" @tap="goSelectAddress">
                <view class="shipper-address-title">寄件地址</view>
                <view class="flex1">
                    <view class="normal">
                        <text>{{ address.contact || ''}}</text>
                        <text class="ml20">{{ address.telephone || ''}}</text>
                    </view>
                    <view class="mt10 sm lighter">
                        {{ `${address.province || ''} ${address.city || ''} ${address.district || ''} ${address.address || ''}` }}
                    </view>
                </view>
                <view class="row">
                    <u-icon name="arrow-right" color="#707070" />
                </view>
                <u-form-item prop="address" v-model="form.address_id"></u-form-item>
            </view>
            
            
            <!-- 收件物流信息 -->
            <view class="addressee">
                <!-- 物流公司 -->
                <u-form-item prop="express" :border-bottom="false">
                    <view class="row">
                        <view class="addressee-label">物流公司</view>
                        <view class="flex1 row input-logistics" @tap="onExpress">
                            <u-input class="flex1" v-model="form.express" disabled placeholder="请输入物流公司名称" />
                            <u-icon name="arrow-down" color="#707070" size="28" />                            
                        </view>
                    </view>
                </u-form-item>
                <!-- 快递单号 -->
                <u-form-item prop="invoice" :border-bottom="false">
                    <view class="row">
                        <view class="addressee-label">快递单号</view>
                        <u-input 
						  class="flex1" 
						  v-model="form.invoice" 
						  placeholder="请输入快递单号" 
						/>
                    </view>
                </u-form-item>
                <!-- 备注说明 -->
  <!--              <u-form-item prop="remark" :border-bottom="false">
                    <view class="row">
                        <view class="addressee-label" style="align-self: flex-start">备注说明</view>
                        <u-input class="flex1" 
                          type="textarea" 
                          v-model="form.remarks" 
                          :clearable="false" 
                          :custom-style="{padding: '20rpx 0'}" 
                          placeholder="选填"
                        />
                    </view>
                </u-form-item> -->
            </view>
            
            
            <!-- 上传凭证 -->
<!--            <view class="logistics-picture mt20">
                <u-form-item prop="picture">
                     <view>
						<text>拍照凭证</text>
						<text class="muted ml10">(请上传快递单号凭证）</text>
					</view>
                     <u-upload
                       ref="uUpload" 
                       :auto-upload="false" 
                       max-count="1" 
                       width="162"
                       height="162"
                       :custom-btn="true"
                       :border-bottom="false"
                       @on-remove="handlePictureRemove"
                       @on-choose-complete="handlePictureUpload"
                     >
                         <view slot="addBtn" class="logistics-picture-button--upload">
                             <u-icon name="/static/images/icon_camera.png" width="54" />
                             <view class="xs normal">上传图片</view>
                         </view>
                     </u-upload>
                </u-form-item>
            </view> -->
        </u-form>

        <!-- 物流公司选择Select -->
		<!-- #ifndef MP-ALIPAY -->
        <u-select v-model="showSelectExpress" mode="single-column" :list="express" @confirm="selectExpress" />
		<!-- #endif -->

        <!-- 功能 -->
        <view>
            <view class="recycle-logistics-submit" @tap="submitExpress">我已寄出</view>
        </view>
    </view>
</template>


<script>
    import { uploadFile } from '@/utils/tools.js';
    import { postGoodsMail } from '@/api/recycle.js';
    
    export default {
        data() {
            return {
                // 表单数据
                form: {
                    order_id: '',       // 订单ID
                    address_id: '',     // 寄件地址ID
                    express: '',        // 物流公司名
                    express_id: '',     // 物流公司ID
                    invoice: '',        // 物流单号
                    remarks: '',        // 备注说明
                    pictures: [],       // 图片
                },
                showSelectExpress: false,   // 物流公司 -- 弹出层
                address: null,              // 回收地址
                express: [],                // 物流公司列表
                // 表单验证
                rules: {
                	address: [{ 
                        validator: () => !!this.form.address_id,
                        message: '请输入寄件地址', 
                	}],
                    express: [{
                        required: true, 
                        message: '请选择物流公司', 
                    }],
                    invoice: [{
                        required: true, 
                        message: '请输入物流单号', 
                    }, {
						pattern: /^[A-Za-z0-9]+$/,
						message: '物流单号不合法', 
					}]
                }
            }
        },
        
        methods: {
            // 跳转到选择地址
            goSelectAddress() {
                uni.navigateTo({
                    url: '/pages/user_address/user_address?type=1'
                })
            },
			
			// 点击物流公司
			onExpress() {
				// #ifndef MP-ALIPAY
				this.showSelectExpress = true;
				// #endif
				
				// #ifdef MP-ALIPAY
				const mapExpress = new Map();
				const express = this.express.map((item, index) => {
					mapExpress.set(index, item.value);
					return item.label;
				});
				
				my.optionsSelect({
					title: "物流公司",
					optionsOne: express,
					success: ({
						selectedOneIndex: index,
						selectedOneOption: label,
					}) => {
						const expressID = mapExpress.get(index);
						
						this.$set(this.form, 'express', label);
						this.$set(this.form, 'express_id', expressID);
					}
				});
				// #endif
			},
            
            // 选择物流公司
            selectExpress(e) {
                const express = e[0];
                this.$set(this.form, 'express', express.label);
                this.$set(this.form, 'express_id', express.value);
            },
            
            // 图片上传
            handlePictureUpload(lists, index) {
                uni.showLoading({
                  title: '正在上传中...',
                  mask: true
                });
                
                const LEN = lists.length;
                for (let i = this.form.pictures.length; i < LEN; ++i) {
                    const file = {...lists[i]};
                    uploadFile(file.url).then(res => {
                       uni.hideLoading();
                       this.form.pictures.push(res.url);
                    });
                }
            },
            
            // 图片删除
            handlePictureRemove(index, lists, name) {
                this.form.pictures.splice(index, 1);
            },
            
            // 提交物流信息
            submitExpress() {
                this.$refs.uForm.validate(valid => {
                    if (valid) {
                        const form = this.form;
                        
                        postGoodsMail({ 
                            type: 'submit',
                            ro_id: form.order_id,
                            address_id: form.address_id,
                            shipping_id: form.express_id,
                            invoice_no: form.invoice,
                            remarks: form.remarks,
                            images: form.pictures
                        }).then(res => {
                            if (res.code != 1) return;

                            uni.showToast({ title: '提交成功' });
                            setTimeout(() => {
                                uni.navigateBack();
                            }, 500);
                        });
                        
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        },
        
        onLoad(options) {
            const order_id = options.id;
            this.form.order_id = order_id;
            
            // 地址选择
            uni.$on("selectaddress", e => {
                const id = e.id;
                const address = e.address;
                
                this.address = address;
                this.form.address_id = id;
            });
            
            // 请求数据初始化
            postGoodsMail({ type: 'info' }).then(res => {
                const data = res.data;
                this.address = data.address;
                this.form.address_id = data.address.id;
                
                // 物流公司格式化，用于选择器
                const express = data.express;
                this.express.length = 0;
                express.forEach(item => {
                    this.express.push({ 
                        label: item.name, 
                        value: item.id 
                    });
                });
            });
        },
        
        onReady() {
            // 表单检验
        	this.$refs.uForm.setRules(this.rules);
        },
    }
</script>


<style scoped>
    .recycle_logistics_form-container {
        padding: 20rpx;
    }
    
    .shipper-address {
        display: flex;
        justify-content: space-between;
        padding: 20rpx;
        border-radius: 10px;
        line-height: 1.3em;
        background-color: #FFFFFF;
    }
    
    .shipper-address-title {
        flex-shrink: 0;
        width: 146rpx;
        color: #999999;
    }
    
    .addressee {
        padding: 0 20rpx;
        border-radius: 10px;
        margin-top: 20rpx;
        background-color: #FFFFFF;
    }
    
    .addressee-label {
        width: 146rpx;
    }
    
    .input-logistics {
        position: relative;
    }
    
    .input-logistics::before {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: 9;
        display: block;
        height: 100%;
        content: '';
    }
    
    .logistics-picture {
        padding: 0 20rpx;
        border-radius: 10px;
        background-color: #FFFFFF;
    }
    
    .logistics-picture-button--upload {
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 162rpx;
        height: 162rpx;
        border: 2rpx dashed #CCCCCC;
        border-radius: 5px;
    }
    
    .recycle-logistics-submit {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 84rpx;
        margin-top: 40rpx;
        font-size: 30rpx;
        border-radius: 30px;
        background-image: linear-gradient(to right, #24A3FF, #3187FD);
        color: #FFFFFF;
    }
    
    .popup-logistics {
        width: 640rpx;
        height: 840rpx;
        padding: 30rpx;
        border-radius: 10px;
        background-color: #FFFFFF;
    }
    
    .popup-logistics-title {
        padding-bottom: 40rpx;
        text-align: center;
        font-size: 34rpx;
        color: #333333;
    }
</style>
